package com.yuyou.fn.crm.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.entity.CustomerResource;
import com.yuyou.fn.crm.entity.VisitMonitor;
import com.yuyou.fn.crm.mapper.CustomerResourceMapper;
import com.yuyou.fn.crm.service.ICrmDepartmentService;
import com.yuyou.fn.crm.service.ICustomerResourceService;
import com.yuyou.fn.crm.service.IVisitMonitorService;
import com.yuyou.fn.crm.service.IVisitService;
import com.yuyou.fn.crm.vo.AnalyzeStatResultOfCustomerResourceVo;
import com.yuyou.fn.crm.vo.AnalyzeStudentOfCustomerResourceVo;
import com.yuyou.fn.crm.vo.CustomerResourceImportNumVo;
import com.yuyou.fn.crm.vo.CustomerResourceQueryVo;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.report.entity.MergeStudentRegDetail;
import com.yuyou.fn.report.service.IMergeStudentRegDetailService;
import com.yuyou.fn.report.vo.StudentRegDetailQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *
 * CustomerResource 表数据服务层接口实现类
 *
 */
@Service
public class CustomerResourceServiceImpl extends SuperServiceImpl<CustomerResourceMapper, CustomerResource,Long> implements ICustomerResourceService {

    @Resource
    private ICampusService campusService;

    @Resource
    private ITeacherService teacherService;

    @Resource
    private IVisitMonitorService visitMonitorService;

    @Resource
    private ICrmDepartmentService crmDepartmentService;

    @Resource
    private IMergeStudentRegDetailService mergeStudentRegDetailService;

    @Resource
    private IVisitService visitService;

    @Override
    public List<CustomerResource> findCustomerResourceByMarketImportId(Long marketImportId) {
        Example<CustomerResource> example = CustomerResource.createExample();
        example.createCriteria().andEqualTo("marketImportId" ,marketImportId);
        return findListByExample(example);
    }

    @Override
    public void updateCustomerResourceStudentId(Long customerResourceId, Long studentId) {
        CustomerResource update = new CustomerResource();
        update.setCustomerResourceId(customerResourceId);
        update.setStudentId(studentId);
        updateSelectiveById(update);

    }

    @Override
    public boolean exist(String studentName, String phoneNo, String projectName, Date date) {
        Example<CustomerResource> example = CustomerResource.createExample();
        example.createCriteria()
                .andEqualTo("studentName",studentName)
                .andEqualTo("phoneNo",phoneNo)
                .andEqualTo("projectName",projectName)
                .andGreaterThan("createTime",date ).andLessThan("createTime", DateUtils.addDays(date, 1 ));
        return countByExample(example) > 0 ;
    }

    @Override
    public Page<CustomerResource> findCustomerResourceByQuery(DataPermission dataPermission, CustomerResourceQueryVo queryVo, int pageNo, int pageSize) {
        if(queryVo.getCreateTimeOfEnd() != null ){
            queryVo.setCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getCreateTimeOfEnd()));
        }
        if (queryVo.getProjectTimeOfEnd()!=null){
            queryVo.setProjectTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getProjectTimeOfEnd()));
        }

        if(queryVo.getAlloCreateTimeOfEnd() != null ){
            queryVo.setAlloCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getAlloCreateTimeOfEnd()));
        }

        if(queryVo.getFollowCreateTimeOfEnd() != null ){
            queryVo.setFollowCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getFollowCreateTimeOfEnd()));
        }


        Example<CustomerResource> example = CustomerResource.createExample();
        if (queryVo.getOrderByStudent()!=null && queryVo.getOrderByStudent()==1){
            example.orderBy("studentId");
        }
        if (queryVo.getDescByAlloCreateTime()){
            example.orderBy("alloCreateTime").desc();
        }else {
            example.orderBy("createTime").desc();
        }


        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillConditionForAreaTeamPermission(criteria,dataPermission.getAreaTeamIds());
        CriteriaUtils.fillCondition(criteria,queryVo);
        criteria.andEqualTo("validateStatus" ,1 );

        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("(campus_id is null ");
        if (Utils.checkListNotEmpty(dataPermission.getCampusIds())){
            stringBuffer.append(" or campus_id in ("+StringUtils.join(dataPermission.getCampusIds(),',')+")");
        }

        //criteria.in("campusId" , dataPermission.getCampusIds() );
        stringBuffer.append( ")");
        criteria.andCondition(stringBuffer.toString());

        return findPageByExample(example,pageNo,pageSize );
    }

    @Override
    public List<CustomerResource> findCustomerResourceByPhone(String phoneNo,Date lessCreateTime) {
        Example<CustomerResource> example=CustomerResource.createExample();
        example.createCriteria().andEqualTo("phoneNo",phoneNo).andLessThanOrEqualTo("createTime",lessCreateTime);
        return this.findListByExample(example);
    }

    @Override
    public List<CustomerResource> findCustomerResourceByCourseOrderId(long courseOrderId) {
        Example<CustomerResource> example=CustomerResource.createExample();
        example.createCriteria().andEqualTo("courseOrderId",courseOrderId);
        return this.findListByExample(example);
    }

    @Override
    @Transactional
    public void deleteByCustomerResourceIds(List<Long> customerResourceIds) {
        if (Utils.checkListEmpty(customerResourceIds)){
            return;
        }
        visitService.deleteByCustomerResourceIds(customerResourceIds);
        visitMonitorService.deleteByCustomerResourceIds(customerResourceIds);
        this.deleteBatchIds(customerResourceIds);
    }

    @Override
    public Long countCustomerResourceByQuery(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        if(queryVo.getCreateTimeOfEnd() != null ){
            queryVo.setCreateTimeOfEnd(DateUtils.addDays(queryVo.getCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getAlloCreateTimeOfEnd() != null ){
            queryVo.setAlloCreateTimeOfEnd(DateUtils.addDays(queryVo.getAlloCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getFollowCreateTimeOfEnd() != null ){
            queryVo.setFollowCreateTimeOfEnd(DateUtils.addDays(queryVo.getFollowCreateTimeOfEnd(),1 ));
        }

        Example<CustomerResource> example = CustomerResource.createExample();

        example.orderBy("createTime").desc();
        if (queryVo.getOrderByStudent()!=null && queryVo.getOrderByStudent()==1){
            example.orderBy("studentId");
        }
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillConditionForAreaTeamPermission(criteria,dataPermission.getAreaTeamIds());
        CriteriaUtils.fillCondition(criteria,queryVo);
        criteria.andEqualTo("validateStatus" ,1 );
        criteria.andIn("campusId" , dataPermission.getCampusIds() );


        return countByExample(example);
    }

    @Override
    public SXSSFWorkbook exportCustomerResource(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        Page<CustomerResource> page = this.findCustomerResourceByQuery(dataPermission,queryVo,1,50000 );
        return customerResource2excel(page.getRecords());
    }

    public static SXSSFWorkbook customerResource2excel(List<CustomerResource> customerResourceList) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("资源分配");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "学生姓名","电话号码","就读年级","性别", "分配校区","紧急程度", "项目活动名称","项目活动日期", "分配状态", "分配时间","跟进状态","抢占人","导入时间", "导入部门", "资源类别","来源大类", "来源小类","备注","分配人"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (customerResourceList!=null){
            for (CustomerResource customerResource : customerResourceList) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getSex()==null?"":customerResource.getSex()==1?"男":customerResource.getSex()==2?"女":"未设置");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getPriority()==null?"":customerResource.getPriority()==0?"低":customerResource.getPriority()==1?"中":"高");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getProjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getProjectTime()==null?"":Utils.formatDate(customerResource.getProjectTime(),"yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloStatus()==null?"":customerResource.getAlloStatus()==0?"否":"是");

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloCreateTime()==null?"":Utils.formatDate(customerResource.getAlloCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getVisitStatus()==null?"":customerResource.getVisitStatus()==0?"未跟进":"已跟进");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getFollowOperatorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getCreateTime()==null?"":Utils.formatDate(customerResource.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getDepartmentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getCustomerResourceType()==null?"":customerResource.getCustomerResourceType()==0?"旧资源":"新资源");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getBigCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getSmallCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getRemark()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getAlloOperatorName()));

            }
        }


        return excel;
    }

    @Override
    public Page<CustomerResource> findCanVisitCustomerResourceByQuery(DataPermission dataPermission, CustomerResourceQueryVo queryVo, int pageNo, int pageSize) {
        if(queryVo.getCreateTimeOfEnd() != null ){
            queryVo.setCreateTimeOfEnd(DateUtils.addDays(queryVo.getCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getAlloCreateTimeOfEnd() != null ){
            queryVo.setAlloCreateTimeOfEnd(DateUtils.addDays(queryVo.getAlloCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getFollowCreateTimeOfEnd() != null ){
            queryVo.setFollowCreateTimeOfEnd(DateUtils.addDays(queryVo.getFollowCreateTimeOfEnd(),1 ));
        }

        Example<CustomerResource> example = CustomerResource.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition(" 1=1 and (visit_status=0 or (again_visit_status=1 AND again_visit_time<= '"+Utils.formatDate(TimeUtils.now(),"yyyy-MM-dd HH:mm:ss")+"'))");

        CriteriaUtils.fillConditionForAreaTeamPermission(criteria,dataPermission.getAreaTeamIds());
        CriteriaUtils.fillCondition(criteria,queryVo);
        criteria.andEqualTo("validateStatus" ,1 );
        criteria.andIn("campusId" , dataPermission.getCampusIds() );

        return findPageByExample(example,pageNo,pageSize );
    }

    @Override
    public Long countCanVisitCustomerResourceByQuery(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        if(queryVo.getCreateTimeOfEnd() != null ){
            queryVo.setCreateTimeOfEnd(DateUtils.addDays(queryVo.getCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getAlloCreateTimeOfEnd() != null ){
            queryVo.setAlloCreateTimeOfEnd(DateUtils.addDays(queryVo.getAlloCreateTimeOfEnd(),1 ));
        }

        if(queryVo.getFollowCreateTimeOfEnd() != null ){
            queryVo.setFollowCreateTimeOfEnd(DateUtils.addDays(queryVo.getFollowCreateTimeOfEnd(),1 ));
        }

        Example<CustomerResource> example = CustomerResource.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition(" 1=1 and (visit_status=0 or (again_visit_status=1 AND again_visit_time<= '"+Utils.formatDate(TimeUtils.nowDate(),"yyyy-MM-dd")+"'))");

        CriteriaUtils.fillConditionForAreaTeamPermission(criteria,dataPermission.getAreaTeamIds());
        CriteriaUtils.fillCondition(criteria,queryVo);
        criteria.andEqualTo("validateStatus" ,1 );
        criteria.andIn("campusId" , dataPermission.getCampusIds() );

        return countByExample(example);
    }

    @Override
    public boolean takeCustomerResource(Long customerResourceId, Principals.Principal principal) {
        Example<CustomerResource> example = CustomerResource.createExample();
        example.createCriteria().andEqualTo("customerResourceId" ,customerResourceId ).andEqualTo("followStatus",0);

        CustomerResource update = new CustomerResource();
        update.setFollowStatus(1);
        update.setFollowOperatorId(principal.id);
        update.setFollowOperatorName(principal.name);
        update.setFollowCreateTime(TimeUtils.now());
        boolean b = updateSelectiveByExample(update, example);
/*        if(b){
            Threads.dispatch(()->createVisitMonitor( Arrays.asList(customerResourceId) ));
        }*/
        return b ;

    }



    @Override
    public boolean alloCampus(List<Long> customerResourceIds, Long campusId , Principals.Principal principal) {

        Validate.notNull(customerResourceIds,"Required customerResourceIds");
        Validate.notNull(campusId,"Required campusId");

        if(customerResourceIds.isEmpty() ){
            return false ;
        }

        Example<CustomerResource> example = CustomerResource.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("customerResourceId" ,customerResourceIds ).andEqualTo("alloStatus" ,0 );

        String campusName = campusService.findCampusNameByCampusId(campusId);
        CustomerResource update = new CustomerResource();
        update.setAlloStatus(1);
        update.setAlloOperatorId(principal.id);
        update.setAlloOperatorName(principal.name);
        update.setAlloCreateTime(TimeUtils.now());
        update.setCampusId(campusId);
        update.setCampusName(campusName);
        update.setUpdateTime(TimeUtils.now());
        boolean b  = updateSelectiveByExample(update,example);
        if(b){

            Threads.dispatch(()->createVisitMonitor(customerResourceIds ));
        }
        return b ;

    }


    @Override
    public boolean alloFollow(List<Long> customerResourceIds, Long followId, Principals.Principal principal) {
        Validate.notNull(customerResourceIds,"Required customerResourceIds");
        Validate.notNull(followId,"Required followId");

        if( customerResourceIds.isEmpty() ){
            return false ;
        }

        Example<CustomerResource> example = CustomerResource.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("customerResourceId" ,customerResourceIds ).andEqualTo("followStatus",0);

        CustomerResource update = new CustomerResource();
        Teacher teacher = teacherService.findById(followId, "teacherName");
        update.setFollowStatus(1);
        update.setFollowOperatorName(teacher.getTeacherName());
        update.setFollowOperatorId(followId);
        update.setFollowCreateTime(TimeUtils.now());
        update.setUpdateTime(TimeUtils.now());

        boolean b  = updateSelectiveByExample(update,example);

        return b ;
    }

    @Override
    public List<AnalyzeStatResultOfCustomerResourceVo> analyzeCustomerResource(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        Page<CustomerResource> page = findCustomerResourceByQuery(dataPermission, queryVo, 1, 10000);
        List<CustomerResource> customerResources = page.getRecords();
        if(customerResources == null || customerResources.isEmpty() ){
            return Collections.EMPTY_LIST;
        }
        List<Long> customerResourceIds = BeanUtils.toList(customerResources,"customerResourceId");

        List<String> phoneNos=BeanUtils.toList(customerResources,"phoneNo");
        StudentRegDetailQueryVo studentRegDetailQueryVo=new StudentRegDetailQueryVo();
        studentRegDetailQueryVo.setRegStatus(0);
        List<MergeStudentRegDetail> mergeStudentRegDetailList =mergeStudentRegDetailService.findByStudentPhoneNosQueryVo(phoneNos,studentRegDetailQueryVo);
        Map<String, List<MergeStudentRegDetail>> studentPhoneNoMap = BeanUtils.toGroup(mergeStudentRegDetailList, "studentPhoneNo");

        // List<AggregationOfStudentReg> aggregationOfStudentRegs = autoMapper.statStudentReg(customerResourceIds);
        List<VisitMonitor> visitMonitors = visitMonitorService.findVisitMonitorByCustomerResourceIds(customerResourceIds);
      //  Map<String,AggregationOfStudentReg> customerResourceIdStudentId2AggregationOfStudentReg = BeanUtils.toMap(aggregationOfStudentRegs,input -> input.getCustomerResourceId()+"||" + input.getStudentId() );
        Map<Long,VisitMonitor> customerResourceId2VisitMonitor = BeanUtils.toMap(visitMonitors,"customerResourceId");

        Map<String , List<CustomerResource>> customerResourceGroup = BeanUtils.toGroup(customerResources, input -> input.getAreaTeamName() + "||" + input.getCampusName() + "||" + input.getProjectName() + "||"+Utils.formatDate(input.getProjectTime(),"yyyy-MM-dd")+ "||" + input.getBigCategory() +"||" + input.getSmallCategory()  );

        List<AnalyzeStatResultOfCustomerResourceVo> list  = new ArrayList<>(customerResourceGroup.size());
        for(Map.Entry<String , List<CustomerResource>> entry : customerResourceGroup.entrySet() ){
            String[] keys = entry.getKey().split("\\|\\|");
            AnalyzeStatResultOfCustomerResourceVo analyzeStatResultOfCustomerResourceVo = new AnalyzeStatResultOfCustomerResourceVo();
            analyzeStatResultOfCustomerResourceVo.setAreaTeamName(keys[0]);
            analyzeStatResultOfCustomerResourceVo.setCampusName(keys[1].equals("null")?"":keys[1]);
            analyzeStatResultOfCustomerResourceVo.setProjectName(keys[2]);
            analyzeStatResultOfCustomerResourceVo.setProjectTime(keys[3]);
            analyzeStatResultOfCustomerResourceVo.setBigCategory(keys[4]);
            analyzeStatResultOfCustomerResourceVo.setSmallCategory(keys[5]);

            for(CustomerResource customerResource : entry.getValue() ){
                analyzeStatResultOfCustomerResourceVo.setStudentAmount(analyzeStatResultOfCustomerResourceVo.getStudentAmount() + 1 );
               // AggregationOfStudentReg aggregationOfStudentReg = customerResourceIdStudentId2AggregationOfStudentReg.get(customerResource.getCustomerResourceId() + "||" + customerResource.getStudentId());
            /*    if(aggregationOfStudentReg != null ){
                    analyzeStatResultOfCustomerResourceVo.setRegStudentAmount(analyzeStatResultOfCustomerResourceVo.getRegStudentAmount() + 1 );
                    analyzeStatResultOfCustomerResourceVo.setRegAmount(analyzeStatResultOfCustomerResourceVo.getRegAmount() + aggregationOfStudentReg.getRegAmount() );
                    analyzeStatResultOfCustomerResourceVo.setTotalAmount(analyzeStatResultOfCustomerResourceVo.getTotalAmount().add(aggregationOfStudentReg.getTotalAmount()));
                }*/
                List<MergeStudentRegDetail> mergeStudentRegDetails =studentPhoneNoMap.get(customerResource.getPhoneNo());
                Map<Long,Integer> map=new HashMap<>();
                if (mergeStudentRegDetails !=null){
                    for (MergeStudentRegDetail mergeStudentRegDetail : mergeStudentRegDetails){
                        if (customerResource.getCreateTime().getTime()<= mergeStudentRegDetail.getCreateTime().getTime()){
                            int studentNum=0;
                            if (!map.containsKey(mergeStudentRegDetail.getStudentId())){
                                studentNum=1;
                                map.put(mergeStudentRegDetail.getStudentId(),1);
                            }
                            analyzeStatResultOfCustomerResourceVo.setRegStudentAmount(analyzeStatResultOfCustomerResourceVo.getRegStudentAmount() + studentNum );
                            analyzeStatResultOfCustomerResourceVo.setRegAmount(analyzeStatResultOfCustomerResourceVo.getRegAmount() + 1 );
                            analyzeStatResultOfCustomerResourceVo.setTotalAmount(analyzeStatResultOfCustomerResourceVo.getTotalAmount().add((mergeStudentRegDetail.getPayAmount().subtract(mergeStudentRegDetail.getRefundAmount()==null?BigDecimal.ZERO: mergeStudentRegDetail.getRefundAmount()))));

                        }
                    }
                }



                if(customerResource.getVisitStatus() == 0 ){
                    analyzeStatResultOfCustomerResourceVo.setNotVisitAmount(analyzeStatResultOfCustomerResourceVo.getNotVisitAmount() + 1 );
                }

                VisitMonitor visitMonitor = customerResourceId2VisitMonitor.get(customerResource.getCustomerResourceId());
                if(visitMonitor != null ){
                    if(visitMonitor.getMonitorStatus() == 1 ){
                        if(visitMonitor.getAlertStatus() == 0 ){
                            analyzeStatResultOfCustomerResourceVo.setOntimeAmount(analyzeStatResultOfCustomerResourceVo.getOntimeAmount() + 1 );
                        }else if(visitMonitor.getAlertStatus() == 1 ){
                            analyzeStatResultOfCustomerResourceVo.setTimeoutAmount(analyzeStatResultOfCustomerResourceVo.getTimeoutAmount() + 1 );
                        }

                    }
                }
            }
            list.add(analyzeStatResultOfCustomerResourceVo);
        }
        return list ;

    }

    private void createVisitMonitor(List<Long> customerResourceIds  ) {
        List<CustomerResource> customerResourceList=this.findByIds(customerResourceIds);
        visitMonitorService.createVisitMonitor(customerResourceList) ;
    }

    @Override
    public Page<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResource(DataPermission dataPermission, CustomerResourceQueryVo queryVo, StudentRegDetailQueryVo studentRegDetailQueryVo, int pageNo, int pageSize) {
        //queryVo.setOrderByStudent(1);
        queryVo.setDescByAlloCreateTime(true);
        Page<CustomerResource> page = findCustomerResourceByQuery(dataPermission, queryVo, pageNo, pageSize);
        Page<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResourceVoPage=Utils.newPage(page);
        List<CustomerResource> customerResources = page.getRecords();
        if(customerResources == null || customerResources.isEmpty() ){
            return analyzeStudentOfCustomerResourceVoPage;
        }

    /*    List<Long> studentIds=BeanUtils.toList(customerResources,"studentId");
        studentIds=Utils.removeDuplicate(studentIds);
        studentRegDetailQueryVo.setRegStatus(0);
        List<StudentRegDetail> studentRegDetailList=mergeStudentRegDetailService.findByStudentIdsQueryVo(studentIds,studentRegDetailQueryVo);

        Map<Long, List<StudentRegDetail>> studentRegMap = BeanUtils.toGroup(studentRegDetailList, "studentId");
*/

        List<String> studentPhoneNos=BeanUtils.toList(customerResources,"phoneNo");
        studentPhoneNos=Utils.removeDuplicate(studentPhoneNos);
        studentRegDetailQueryVo.setRegStatusList(Arrays.asList(0,3));
        List<MergeStudentRegDetail> mergeStudentRegDetailList =mergeStudentRegDetailService.findByStudentPhoneNosQueryVo(studentPhoneNos,studentRegDetailQueryVo);

        Map<String,List<MergeStudentRegDetail>> studentRegMap = BeanUtils.toGroup(mergeStudentRegDetailList, "studentPhoneNo");


        List<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResourceVoList=new ArrayList<>(customerResources.size());

        Map<String,List<CustomerResource>> phoneCustomerResourceMap=BeanUtils.toGroup(customerResources,"phoneNo");



        for (CustomerResource customerResource:customerResources){
            AnalyzeStudentOfCustomerResourceVo analyzeStudentOfCustomerResourceVo=new AnalyzeStudentOfCustomerResourceVo();
            Long studentId=customerResource.getStudentId();
            String phoneNo=customerResource.getPhoneNo();
            Long customerResourceCreateTime=customerResource.getCreateTime().getTime();

            BeanUtils.copyProperties(analyzeStudentOfCustomerResourceVo,customerResource);

            List<MergeStudentRegDetail> oneMergeStudentRegDetailList =studentRegMap.get(phoneNo);
            if (oneMergeStudentRegDetailList !=null){
                for (MergeStudentRegDetail mergeStudentRegDetail : oneMergeStudentRegDetailList){
                    Long studentRegTime= mergeStudentRegDetail.getCreateTime().getTime();
                    if (customerResourceCreateTime<=studentRegTime){
                        Integer regAmount=analyzeStudentOfCustomerResourceVo.getRegAmount()+1;
                        analyzeStudentOfCustomerResourceVo.setRegAmount(regAmount);
                        BigDecimal totalAmount= mergeStudentRegDetail.getPayAmount().subtract(mergeStudentRegDetail.getRefundAmount());
                        analyzeStudentOfCustomerResourceVo.setTotalAmount(analyzeStudentOfCustomerResourceVo.getTotalAmount().add(totalAmount));
                        Long checkTime=analyzeStudentOfCustomerResourceVo.getFirstRegTime()==null? mergeStudentRegDetail.getCreateTime().getTime():analyzeStudentOfCustomerResourceVo.getFirstRegTime().getTime();
                        if (mergeStudentRegDetail.getCreateTime().getTime()<=checkTime){
                            analyzeStudentOfCustomerResourceVo.setFirstRegTime(mergeStudentRegDetail.getCreateTime());
                        }
                    }
                }
            }
            analyzeStudentOfCustomerResourceVoList.add(analyzeStudentOfCustomerResourceVo);
        }
  /*      Collections.sort(analyzeStudentOfCustomerResourceVoList, new Comparator<AnalyzeStudentOfCustomerResourceVo>() {
            @Override
            public int compare(AnalyzeStudentOfCustomerResourceVo o1, AnalyzeStudentOfCustomerResourceVo o2) {
                return o1.getStudentId().compareTo(o2.getStudentId());
            }
        });*/
        analyzeStudentOfCustomerResourceVoPage.setRecords(analyzeStudentOfCustomerResourceVoList);
        return analyzeStudentOfCustomerResourceVoPage;

    }

    @Override
    public SXSSFWorkbook exportAnalyzeStudentOfCustomerResource(DataPermission dataPermission, CustomerResourceQueryVo queryVo,StudentRegDetailQueryVo studentRegDetailQueryVo) {
        Page<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResourceVoPage = this.analyzeStudentOfCustomerResource(dataPermission, queryVo,studentRegDetailQueryVo, 1, 20000);
        return analyzeStudentOfCustomerResource2excel(analyzeStudentOfCustomerResourceVoPage.getRecords());
    }


    public static SXSSFWorkbook analyzeStudentOfCustomerResource2excel(List<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResourceVos) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("资源明细");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "学生姓名", "联系电话","区域", "分配校区","项目名称", "分配时间", "来源大类", "来源小类", "资源类别", "导入部门","导入人","学生年级","是否跟进","首次成交时间","成交科数","成交金额"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (analyzeStudentOfCustomerResourceVos!=null){
            for (AnalyzeStudentOfCustomerResourceVo analyzeStudentOfCustomerResourceVo : analyzeStudentOfCustomerResourceVos) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getAreaTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getProjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getAlloCreateTime()==null?"":Utils.formatDate(analyzeStudentOfCustomerResourceVo.getAlloCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getBigCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getSmallCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getCustomerResourceType()==null?"":analyzeStudentOfCustomerResourceVo.getCustomerResourceType()==1?"新资源":"旧资源");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getDepartmentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getImportOperatorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(analyzeStudentOfCustomerResourceVo.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getVisitStatus()==null?"":analyzeStudentOfCustomerResourceVo.getVisitStatus()==0?"未跟进":"已跟进");


                cell = row.createCell(cellNum++);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getFirstRegTime()==null?"":Utils.formatDate(analyzeStudentOfCustomerResourceVo.getFirstRegTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getRegAmount());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(analyzeStudentOfCustomerResourceVo.getTotalAmount()==null?0d:analyzeStudentOfCustomerResourceVo.getTotalAmount().doubleValue());

            }
        }


        return excel;
    }

    @Override
    public void updateDepartmentNameById(Long departmentId, String departmentName) {
        Validate.notNull(departmentId,"Required departmentId");
        CustomerResource customerResource=new CustomerResource();
        customerResource.setDepartmentName(departmentName);
        Example<CustomerResource> example=CustomerResource.createExample();
        example.createCriteria().andEqualTo("departmentId",departmentId);
        this.updateSelectiveByExample(customerResource,example);
    }

    @Override
    public SXSSFWorkbook exportFirstRegOfCustomerResource(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        Page<CustomerResource> customerResourcePage=this.findCustomerResourceByQuery(dataPermission,queryVo,1,50000);

        return firstRegOfCustomerResource2excel(customerResourcePage.getRecords());
    }

    @Override
    public Page<CustomerResource> findRecycleResourceByQueryByQuery(DataPermission dataPermission, CustomerResourceQueryVo queryVo, int pageNo, int pageSize) {
        if(queryVo.getCreateTimeOfEnd() != null ){
            queryVo.setCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getCreateTimeOfEnd()));
        }
        if (queryVo.getProjectTimeOfEnd()!=null){
            queryVo.setProjectTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getProjectTimeOfEnd()));
        }

        if(queryVo.getAlloCreateTimeOfEnd() != null ){
            queryVo.setAlloCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getAlloCreateTimeOfEnd()));
        }

        if(queryVo.getFollowCreateTimeOfEnd() != null ){
            queryVo.setFollowCreateTimeOfEnd(TimeUtils.changeOneDateLastTime(queryVo.getFollowCreateTimeOfEnd()));
        }
        if (queryVo.getRecycleTimeOfEnd()==null || queryVo.getRecycleTimeOfEnd().after(TimeUtils.now())){
            queryVo.setRecycleTimeOfEnd(TimeUtils.now());
        }
        Example<CustomerResource> example = CustomerResource.createExample();
        if (queryVo.getOrderByStudent()!=null && queryVo.getOrderByStudent()==1){
            example.orderBy("studentId");
        }
        if (queryVo.getDescByAlloCreateTime()){
            example.orderBy("alloCreateTime").desc();
        }else {
            example.orderBy("createTime").desc();
        }

        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillConditionForAreaTeamPermission(criteria,dataPermission.getAreaTeamIds());
        CriteriaUtils.fillCondition(criteria,queryVo);
        criteria.andEqualTo("validateStatus" ,1 );
        criteria.andCondition(" (first_reg_num is null or first_reg_num=0)");
        return findPageByExample(example,pageNo,pageSize );
    }

    public static SXSSFWorkbook firstRegOfCustomerResource2excel(List<CustomerResource> customerResourceList) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("首次转化统计");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "学生姓名", "联系电话","区域", "分配校区","项目名称", "分配时间", "来源大类", "来源小类", "资源类别", "导入部门","导入人","学生年级","是否跟进","首次成交时间","首次成交科数","首次成交金额","咨询师","抢占人"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (customerResourceList!=null){
            for (CustomerResource customerResource : customerResourceList) {
                int cellNum = 0;
                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getAreaTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getProjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloCreateTime()==null?"":Utils.formatDate(customerResource.getAlloCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getBigCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getSmallCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getCustomerResourceType()==null?"":customerResource.getCustomerResourceType()==1?"新资源":"旧资源");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getDepartmentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getImportOperatorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getVisitStatus()==null?"":customerResource.getVisitStatus()==0?"未跟进":"已跟进");


                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getFirstRegTime()==null?"":Utils.formatDate(customerResource.getFirstRegTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(customerResource.getFirstRegNum()==null?0:customerResource.getFirstRegNum());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(customerResource.getFirstRegAmount()==null?0d:customerResource.getFirstRegAmount().doubleValue());



                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getCounselorNames()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getFollowOperatorName()));
            }
        }


        return excel;
    }


    @Override
    public SXSSFWorkbook exportCustomerResourceRecycle(DataPermission dataPermission, CustomerResourceQueryVo queryVo) {
        Page<CustomerResource> page = this.findRecycleResourceByQueryByQuery(dataPermission,queryVo,1,50000 );
        return customerResourceRecycle2excel(page.getRecords());
    }

    @Override
    public List<CustomerResourceImportNumVo> findCustomerResourceImportNum(List<String> studentNames, List<String> phoneNos, List<String> projectNames) {
        return this.autoMapper.findCustomerResourceImportNum(studentNames,phoneNos,projectNames);
    }

    public static SXSSFWorkbook customerResourceRecycle2excel(List<CustomerResource> customerResourceList) {

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("资源回收");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[]{ "学生姓名","电话号码","就读年级","性别", "分配校区","紧急程度", "项目活动名称","项目活动日期", "分配状态", "分配时间","跟进状态","抢占人","导入时间", "导入部门", "资源类别","来源大类", "来源小类","备注","分配人"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;

        if (customerResourceList!=null){
            for (CustomerResource customerResource : customerResourceList) {
                int cellNum = 0;

                SXSSFRow row = sheet.createRow(rowNum++);

                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getSex()==null?"":customerResource.getSex()==1?"男":customerResource.getSex()==2?"女":"未设置");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getPriority()==null?"":customerResource.getPriority()==0?"低":customerResource.getPriority()==1?"中":"高");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getProjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getProjectTime()==null?"":Utils.formatDate(customerResource.getProjectTime(),"yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloStatus()==null?"":customerResource.getAlloStatus()==0?"否":"是");

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloCreateTime()==null?"":Utils.formatDate(customerResource.getAlloCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getVisitStatus()==null?"":customerResource.getVisitStatus()==0?"未跟进":"已跟进");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getFollowOperatorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getCreateTime()==null?"":Utils.formatDate(customerResource.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getDepartmentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getCustomerResourceType()==null?"":customerResource.getCustomerResourceType()==0?"旧资源":"新资源");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getBigCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getSmallCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getRemark()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getAlloOperatorName()));

            }
        }


        return excel;
    }

    @Override
    public void updateSignStatusByActivityRegSituationId(long activityRegSituationId,Integer signStatus) {
        Example<CustomerResource> example=CustomerResource.createExample();
        example.createCriteria().andEqualTo("activityRegSituationId",activityRegSituationId);
        CustomerResource customerResource=new CustomerResource();
        customerResource.setSignStatus(signStatus);
        customerResource.setUpdateTime(TimeUtils.now());
        this.updateSelectiveByExample(customerResource,example);
    }
}